package com.zju.DoctorGo.controller;

import com.zju.DoctorGo.dto.MessageFilterDTO;
import com.zju.DoctorGo.entity.Message;
import com.zju.DoctorGo.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping(value = "/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;

    private String normalizeField(String field) {
        if (field == null || field.equals("所有") || field.equals("全部")) {
            return null;
        }
        return field;
    }

    @PostMapping
    public ResponseEntity<?> getMessages(@RequestBody MessageFilterDTO filter) {
        filter.setTitle(normalizeField(filter.getTitle()));
        filter.setDate(normalizeField(filter.getDate()));
        filter.setReceiver(normalizeField(filter.getReceiver()));
        filter.setSender(normalizeField(filter.getSender()));
        List<Message> messages = messageService.getMessages(filter);
        return ResponseEntity.ok(messages);
    }

    @PostMapping("/add")
    public ResponseEntity<?> addMessage(@RequestBody Message message) {
        messageService.addMessage(message);
        return ResponseEntity.ok().body("Message sent successfully");
    }

    @PostMapping("/delete")
    public ResponseEntity<?> deleteMessage(@RequestBody List<Long> messageIds) {
        messageService.deleteMessages(messageIds);
        return ResponseEntity.ok().body("Messages deleted successfully");
    }
}
